package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.Menus;
import com.iot.manage.pojo.User;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.LoginService;
import com.iot.manage.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制层--登陆登出获取菜单列表
 *
 */
@RestController
@RequestMapping("/api/private/v1")
public class LoginController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LoginService loginService;

    /**
     * 用户登陆
     *
     * @param params 用户名、密码
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody JSONObject params) {
        Result result = new Result();
        List<User> userList;
        try {
            // 查询用户是否存在
            userList = loginService.findUserByName(params);
            String token;
            if (userList.size() <= 0) {//用户不存在
                return result.build(null,Code.D401);
            }else{//用户存在
                // 查询用户密码是否正确
                String pass = loginService.findPassByName(params);
                if (!(params.getString("password").equals(pass))) {//密码不正确
                    return result.build(null,Code.D402);
                } else {//密码正确
                    // 设置用户的token
                    token = tokenService.setToken(params.getString("username"));
                    userList.get(0).setToken(token);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.E501);
        }
        return result.build(userList.get(0),Code.S201);
    }

    /**
     * 获取菜单目录结构
     *
     * @return
     */
    @GetMapping("/menus")
    public Result menus(@RequestHeader("token") String token) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Menus> menusList;
        try{
            menusList = loginService.findMenus();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D406);
        }
        return result.build(menusList,Code.S202);
    }

    /**
     * 用户登出
     *
     * @param token token标识
     * @param loginName 用户名
     * @return
     */
    @GetMapping("/logout/{loginName}")
    public Result logout(@RequestHeader("token") String token,
                         @PathVariable("loginName") String loginName) {
        Result result = new Result();
        try{
            // 移除用户的token
            tokenService.removeToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D405);
        }
        return result.build(null,Code.S206);
    }
}
